var selctedFeedId;
// bind mobile events
$(document).on("pageinit pageshow", "#feeds-list", function () {
	validateLoggedInUser();
	requestFeeds();
	bindLogout();
});
$(document).on("pageinit pageshow", "#Offline-feeds-list", function () {
	validateLoggedInUser();
	getSavedFeeds();
	bindLogout();
});
$(document).on("pageinit", "#home", function() {
	initLoginPageComponenets();
});
$(document).on("pageinit", "#signup", function() {
	initSignPageComponenets();
});
$(document).on("pageshow", "#new-feed", function() {
	validateLoggedInUser();
	bindAddFeedEvents();
});
$(document).on("click", ".feed-link", function(event) {
	var id=$(this).attr("data-id");
	selctedFeedId=id;
});

$(document).on("pageshow", "#feed", function () {
	validateLoggedInUser();
	
	if(selctedFeedId)
	{
		readFeed(".content-wrapper", "<h2><a href=\"{0}\" target=\"_blank\">{1}</a></h2><div class=\"feeds\">{2}</div>", "link,title,description",null,selctedFeedId);
	}
	else
		{
		$.mobile.changePage("FeedsList.htm");
		}
	
	bindLogout();
});


function validateLoggedInUser() {
	var isUserLoggedIn = isLoggedIn(); 
	if (!isUserLoggedIn) {
		$.mobile.changePage("index.htm");
	}
	
	return isUserLoggedIn;
}


$(window).resize(function () {
    fixTextSize();
});

function showLoader(message) {
	$.mobile.showPageLoadingMsg(message);
}
function hideLoader() {
	$.mobile.hidePageLoadingMsg();
}

// populate list of items
function populateList(items, hideSavedButton, wrapperId) {
	var template = ['<li class="feed-holder" data-feed="{0}">'];
	if(!hideSavedButton)
	{
		template.push('<div class="drag-explain">');
		template.push('<span class="text">Swipe to save</span>');
		template.push(' <a href="#" data-inline="true" data-mini="true" data-role="button" data-icon="check" ');
		template.push(' data-theme="b" class="ok" data-iconpos="notext">Saved</a> ');
		template.push( '</div>');
	}
	
	template.push('<a data-id="{0}" href="feed.htm" data-transition="slide" class="');
	if(!hideSavedButton)
	{
		template.push('swiper-container ');
	}
	
	template.push('feed-link">');
	if(!hideSavedButton)
	{
		template.push('<div class="swiper-wrapper">');
		template.push('<span class="swiper-slide dummy-slide" data-role="none"></span>');
	  	template.push('<span class="swiper-slide"><span class="feed-text">{1}</span></span>');
	  	template.push('</div>');
	  	template.push('</a>');
	  	template.push(' </li>');
	} else {
		template.push('{1}');
	}

	template.push('</a>');
	template.push(' </li>');

	var feeds = $(items).find("item");
 
	 if (feeds.length === 0) {
		 feeds = items;
	 }
	 
    wrapperId = wrapperId || "#items";
    populateElement(feeds, wrapperId, template.join(""), "id,title", function refresh() {
        $(wrapperId).listview("refresh");
        $(wrapperId+" [data-role=button]").button();
        fixTextSize();
    });
}

// fixing feed text container
function fixTextSize() {
        $(".feed-text").width($(this).width() - 50);
}

function initFeedsPageComponents() {
    $(".swiper-container").each(function (index, elem) {
        $(elem).swiper({
            slidesPerSlide: 1,
            initialSlide: 1,
            slideElement:"span",
            nopeek: true,
            shortSwipes: false,
            onTouchStart: function (swiper) {
                initDragElements(swiper);
            },
            onTouchMove: function (swiper) {
                wasSwiped = true;
                handleDragMovement(swiper);
            },
            onTouchEnd: function () {
            	handleDragRelease();
            }
        });
    });

    initFeedsEvents();
}

function requestFeeds() {
    var deferred = getFeeds();
   
    deferred.done(function(data) {
    	populateList(data);   // "data" is the xml document!
    	initFeedsPageComponents();
     }).fail(function(data) {
         console.log(data); // data is error
     }).always(function(data) {
          // something to always do [optional]
     });
}

function getSavedFeeds()
{
	var deferred = requestSavedFeeds();
	
	deferred.done(function(items) {
		populateList(items, true,"#Offline-items");
	});
}

function login(username, password) {
	
	var deferred = tryLogin(username, password);
	
	deferred.done(function(response) {
		
		$.mobile.changePage("FeedsList.htm");
	}).always(function() {
		//hideLoader();
	});
}
function bindLogout() {
	$(document).off("click",".log-off").on("click",".log-off",function() {
		//showLoader();
		var deferred =requsetLogOutServer();
		deferred.done(function(response) {
			$.mobile.changePage("index.htm");
		}).always(function() {
			//hideLoader();
		});
	});	
}

function bindAddFeedEvents() {
	$(document).off("click", "#add-feed").on("click", "#add-feed", function() {
		//showLoader();
		var deferred = addFeedToServer();
		deferred.done(function(data) {
			$.mobile.back();
		}).always(function() {
		//	hideLoader();
		});
	});
	
	$(document).off("click", "#cancel-feed").on("click", "#cancel-feed", function() {
		$("#add-feed-error").text("").removeClass();
		$("#rss-name").val("");
	    $("#rss-url").val("");
	});
}

/** swiping handling - start **/
var draggedElement = null,
    draggedParent = null,
    explainElem = null,
    explainTextElem = null,
    okIcon = null,
    wasSwiped = false,  // to prevents clicks when swiping
    MIN_PRECENTS_TO_ACCEPT = 0.5;

function staticsCleanup() {
    draggedElement = null;
    draggedParent = null;
    explainElem = null;
    explainTextElem = null;
    okIcon = null;
}

function initDragElements(swiper) {
    draggedElement = swiper;
    draggedParent = $(draggedElement.wrapper).closest(".feed-holder");
    explainElem = $(draggedParent).find(".drag-explain");
    explainTextElem = explainElem.find(".text");
    okIcon = explainElem.find(".ok");
}

function getDragPrecents() {
    var dragWidth = $(explainElem).width() + 15,
        parentWidth = $(draggedParent).width(),
        dragPercents = dragWidth / parentWidth;
    return dragPercents;

}

function handleDragMovement(swiper) {
    var dragPrecents = getDragPrecents();

    explainElem.css({
        "opacity": dragPrecents * 2,
        "width": (swiper.touches.current - swiper.touches.start) + "px",
    });

    if (dragPrecents > 0.5) {
        explainTextElem.text("Release to save");
        okIcon.fadeIn("fast");
    }
    else {
        explainTextElem.text("Swipe to save");
        $(okIcon).fadeOut("fast");
    }

}

function handleDragRelease() {
    if (getDragPrecents() >= MIN_PRECENTS_TO_ACCEPT) {
        var feedId = $(draggedParent).attr("data-feed");
        var deferred = saveFeed(feedId, hideStrip);
        
      //  showLoader("Please wait");
    	deferred.done(function() {
    		hideStrip();
    	}).fail(function() {
    		showStrip();
    		//TODO: show text in case of an error
    		
    		//resetPosition();
    	}).always(function() {
    		hideLoader();
    	});
    } else {
        showStrip();
    }
}

function resetPosition() {
	//draggedElement.wrapper
}

function hideStrip() {
    var finalWidth = $(draggedParent).width();
    animateSliders(finalWidth, animateRemoveItem);
}

function showStrip() {
    animateSliders(0, handleShowItem);
}

function animateSliders(finalWidth, callback) {
    $(explainElem).animate({
        "width": finalWidth,
        "opacity": (finalWidth > 0) ? 1 : 0
    }, "fast", "linear", function() {
        if (typeof(callback) == "function") {
            callback();
        }
    });
}

function handleShowItem() {
    staticsCleanup();
    return false;
}

function animateRemoveItem() {
    var parent = draggedParent;
    var explain = explainElem;
    
    $(parent).animate({
        "height": 0
    }, "fast", "linear");
    
    $(explain).animate({
        "height": 0
    }, "fast", "linear", function() {
        draggedElement.destroy();
        $(parent).remove();
        staticsCleanup();
    });
}

// validates swiping and not clicking
function initFeedsEvents() {
    $(".feed-link").on("swipe vclick", function(event) {
        if (event.type === "swipe") {
            wasSwiped = true;
        } else {
            if (wasSwiped) {
                wasSwiped = false;
                event.preventDefault();
                event.stopPropagation();
                return false;
            }
        }
    });
}	    
/** swiping handling - end **/

